package reduce.fz.com.reduce.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.SparseArrayCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.alibaba.fastjson.TypeReference;

import java.util.List;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.abstracts.AbResponseListener;
import reduce.fz.com.reduce.activity.OtherMeDynamicActivity;
import reduce.fz.com.reduce.activity.TeamDetailActivity;
import reduce.fz.com.reduce.activity.UserDetailActivity;
import reduce.fz.com.reduce.bean.ServiceException;
import reduce.fz.com.reduce.bean.Team;
import reduce.fz.com.reduce.bean.User;
import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.custom.FollowView;
import reduce.fz.com.reduce.custom.LoadingDialog;
import reduce.fz.com.reduce.custom.NetworkImageView;
import reduce.fz.com.reduce.custom.SlidingTabLayout;
import reduce.fz.com.reduce.custom.TouchCallbackLayout;
import reduce.fz.com.reduce.custom.pagerheader.ScrollableFragmentListener;
import reduce.fz.com.reduce.custom.pagerheader.ScrollableListener;
import reduce.fz.com.reduce.custom.pagerheader.ViewPagerHeaderHelper;
import reduce.fz.com.reduce.custom.view.RoundNetworkImageView;
import reduce.fz.com.reduce.fragment.base.BaseFragment;
import reduce.fz.com.reduce.service.TeamService;
import reduce.fz.com.reduce.service.preference.UserPreference;
import reduce.fz.com.reduce.util.HttpUtils;
import reduce.fz.com.reduce.util.ServiceBuilder;

/**
 * A simple {@link Fragment} subclass.
 */
public class UserDetailFragment extends BaseFragment implements ScrollableFragmentListener {

    /*HEADER**/
    private RoundNetworkImageView mUserAvatar;
    private TextView mNickName;
    private FollowView mFollow;

    private LayoutInflater layoutInflater;
    private User user;
    private int mTabHeight;
    //teamHeder高度
    private int mHeaderHeight;
    private int mTouchSlop;
    //viewPager辅助
    private ViewPagerHeaderHelper mViewPagerHeaderHelper;
    private View view;
    //viewPager对象
    private ViewPager mViewPager;
    private SlidingTabLayout slidingTabLayout = null;
    //teamHeader对象
    private static final long DEFAULT_DURATION = 300L;
    private static final float DEFAULT_DAMPING = 1.5f;
    private View mHeaderLayoutView;
    private Interpolator mInterpolator = new DecelerateInterpolator();
    private UserDetailActivity mActivity;
    private SparseArrayCompat<ScrollableListener> mScrollableListenerArrays = new SparseArrayCompat<ScrollableListener>();

    @Override
    public void onFragmentAttached(ScrollableListener fragment, int position) {
        mScrollableListenerArrays.put(position, fragment);
    }

    @Override
    public void onFragmentDetached(ScrollableListener fragment, int position) {
        mScrollableListenerArrays.remove(position);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        user = (User) getArguments().getSerializable("user");
    }

    /**
     * 初始化入口
     *
     * @param view
     */
    public void init(View view) {
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private class ViewPagerAdapter extends FragmentPagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            BaseViewPagerFragment fragment = null;
            switch (position) {
                case 0: {
                    fragment = MyVideoCardListFragment.create(position,user.uid);
                    break;
                }
                case 1: {
                    fragment = AttentionListFragment.create(position, 0,user.uid);
                    break;
                }
                case 2: {
                    fragment = AttentionListFragment.create(position, 1,user.uid);
                    break;
                }
                default:
                    break;

            }
            Bundle args = new Bundle();
            fragment.setListener(UserDetailFragment.this);
            return fragment;
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "作品";
                case 1:
                    return "关注";
                case 2:
                    return "粉丝";
            }
            return "";
        }
    }


    public void initMainWidget(View view) {
        mTabHeight = getResources().getDimensionPixelSize(R.dimen.tabs_height);
        mHeaderHeight = getResources().getDimensionPixelSize(R.dimen.viewpager_header_height);
        mHeaderLayoutView = view.findViewById(R.id.ll_header);
        mViewPager = (ViewPager) view.findViewById(R.id.team_detail_viewpage);
        slidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.team_tabs);
        mViewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager()));
        mViewPager.setOffscreenPageLimit(2);
        slidingTabLayout.setViewPager(mViewPager);
        ViewCompat.setTranslationY(mViewPager, mHeaderHeight);
        mViewPager.setCurrentItem(0);
        slidingTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                Boolean isPub = false;
                Boolean isWitness = false;
                Boolean isStory = false;
                Boolean pubSub = false;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mViewPagerHeaderHelper = new ViewPagerHeaderHelper(getActivity(), new ViewPagerHeaderHelper.OnViewPagerTouchListener() {


            @Override
            public boolean isViewBeingDragged(MotionEvent event) {

                int current = mViewPager.getCurrentItem();


                ScrollableListener listener = mScrollableListenerArrays.valueAt(current);
                Boolean isDragged = listener.isViewBeingDragged(event);
                return isDragged;
            }

            @Override
            public void onMoveStarted(float eventY) {

            }


            @Override
            public void onMove(float eventY, float yDx) {
                float headerTranslationY = ViewCompat.getTranslationY(mHeaderLayoutView) + yDx;
                if (headerTranslationY >= 0) { // pull end
                    headerExpand(0L);


                } else if (headerTranslationY <= -mHeaderHeight) { // push end
                    headerFold(0L);
                } else {
                    ViewCompat.animate(mHeaderLayoutView)
                            .translationY(headerTranslationY)
                            .setDuration(0)
                            .start();
                    ViewCompat.animate(mViewPager)
                            .translationY(headerTranslationY + mHeaderHeight)
                            .setDuration(0)
                            .start();
                }
            }

            @Override
            public void onMoveEnded(boolean isFling, float flingVelocityY) {


                float headerY = ViewCompat.getTranslationY(mHeaderLayoutView); // 0到负数
                if (headerY == 0 || headerY == -mHeaderHeight) {
                    return;
                }

                if (mViewPagerHeaderHelper.getInitialMotionY() - mViewPagerHeaderHelper.getLastMotionY()
                        < -mTouchSlop) {  // pull > mTouchSlop = expand
                    headerExpand(headerMoveDuration(true, headerY, isFling, flingVelocityY));
                } else if (mViewPagerHeaderHelper.getInitialMotionY()
                        - mViewPagerHeaderHelper.getLastMotionY()
                        > mTouchSlop) { // push > mTouchSlop = fold
                    headerFold(headerMoveDuration(false, headerY, isFling, flingVelocityY));
                } else {
                    if (headerY > -mHeaderHeight / 2f) {  // headerY > header/2 = expand
                        headerExpand(headerMoveDuration(true, headerY, isFling, flingVelocityY));
                    } else { // headerY < header/2= fold
                        headerFold(headerMoveDuration(false, headerY, isFling, flingVelocityY));
                    }
                }


            }
        });


        TouchCallbackLayout touchCallbackLayout = (TouchCallbackLayout) view.findViewById(R.id.touch_layout);
        touchCallbackLayout.setTouchEventListener(new TouchCallbackLayout.TouchEventListener() {
            @Override
            public boolean onLayoutInterceptTouchEvent(MotionEvent ev) {
                return mViewPagerHeaderHelper.onLayoutInterceptTouchEvent(ev,
                        mTabHeight + mHeaderHeight);
            }

            @Override
            public boolean onLayoutTouchEvent(MotionEvent ev) {
                return mViewPagerHeaderHelper.onLayoutTouchEvent(ev);
            }
        });
    }

    private long headerMoveDuration(boolean isExpand, float currentHeaderY, boolean isFling,
                                    float velocityY) {

        long defaultDuration = DEFAULT_DURATION;

        if (isFling) {

            float distance = isExpand ? Math.abs(mHeaderHeight) - Math.abs(currentHeaderY)
                    : Math.abs(currentHeaderY);
            velocityY = Math.abs(velocityY) / 1000;

            defaultDuration = (long) (distance / velocityY * DEFAULT_DAMPING);

            defaultDuration =
                    defaultDuration > DEFAULT_DURATION ? DEFAULT_DURATION : defaultDuration;
        }

        return defaultDuration;
    }


    /**
     * team 头部展开
     *
     * @param duration
     */
    private void headerExpand(long duration) {
        ViewCompat.animate(mHeaderLayoutView)
                .translationY(0)
                .setDuration(duration)
                .setInterpolator(mInterpolator)
                .start();

        ViewCompat.animate(mViewPager)
                .translationY(mHeaderHeight)
                .setDuration(duration)
                .setInterpolator(mInterpolator)
                .start();
        mViewPagerHeaderHelper.setHeaderExpand(true);
    }

    /**
     * team 头部隐藏
     *
     * @param duration
     */
    private void headerFold(long duration) {
        ViewCompat.animate(mHeaderLayoutView)
                .translationY(-mHeaderHeight)
                .setDuration(duration)
                .setInterpolator(mInterpolator)
                .start();

        ViewCompat.animate(mViewPager).translationY(0).
                setDuration(duration).setInterpolator(mInterpolator).start();

        mViewPagerHeaderHelper.setHeaderExpand(false);
    }

    /**
     * 获取team详情
     *
     * @param teamid
     */


    /**
     * 初始化team header
     *
     * @param view
     */


    /**
     * 填充teamheader数据
     */


    public UserDetailFragment() {
    }

    public static UserDetailFragment create(User user) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("user", user);

        UserDetailFragment detailFragment = new UserDetailFragment();
        detailFragment.setArguments(bundle);
        return detailFragment;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTouchSlop = ViewConfiguration.get(getActivity()).getScaledTouchSlop();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user_detail, container, false);
        if (getActivity() instanceof TeamDetailActivity)
            mActivity = (UserDetailActivity) getActivity();
        this.view = view;
        this.layoutInflater = LayoutInflater.from(view.getContext());
        init(view);
        initMainWidget(view);
        initTeamHeaderView(view);
        initTeamHeaderData();
        return view;
    }


    public void initTeamHeaderView(View view) {
        mUserAvatar = (RoundNetworkImageView) view.findViewById(R.id.iv_user_avatar);
        mNickName = (TextView) view.findViewById(R.id.tv_user_nickname);
        mFollow = (FollowView) view.findViewById(R.id.tv_follow);

    }

    public void initTeamHeaderData() {
        mUserAvatar.setImageUrl(user.avatar, HttpUtils.getImageLoader());
        mNickName.setText(user.nickname);
        User me = UserPreference.getUser();
        mFollow.setStatus(me.uid, user);
        mFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFollow.doToggleAction();
            }
        });
    }


}
